package database;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import main.Terminal;
import model.Seat;

/**
 * 
 * @author Patrick
 *
 */

public class DBSeat {
	
	private DBConnection con;
	private DBCinema cin;
	
	public DBSeat()
	{
		con = DBConnection.getInstance();
		cin = new DBCinema();	//TODO: <--- how come I need to fix these all the time? -Anders
	}
	
	public Seat getSeat(int id)
	{
		Seat result = null;
		String condition = ("Select id, row, number, cinemano from Seat where id = " + id);
		ResultSet resSet = con.executeResSet(condition);
		try {
			resSet.next();
			int idd = resSet.getInt("id");
			int row = resSet.getInt("row");
			int number = resSet.getInt("number");
			result = new Seat(idd, row, number, cin.getCinema(resSet.getString("cinemano")));
			resSet.getStatement().close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public ArrayList<Seat> getAllSeats(String cinNumber)
	{
		ArrayList<Seat> allSeats = new ArrayList<Seat>();
		String query = "Select id, row, number, cinemano from Seat " +
				"where cinemano = " + cinNumber;
		ResultSet resSet = con.executeResSet(query);
		
		try {
			while(resSet.next())
			{
				allSeats.add(buildSeat(resSet));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return allSeats;
	}
	
	private Seat buildSeat(ResultSet resSet)
	{
		try{
			int id = resSet.getInt("ID");
			int row = resSet.getInt("Row");
			int number = resSet.getInt("Number");
			String cinNum = resSet.getString("CinemaNo");
			return new Seat(id, row, number, cin.getCinema(cinNum));
		}
		catch(Exception e)
		{
			Terminal.say("Could not build seat!", e);	//<-- please remember there so debugging becomes WAY easier.. -Anders
			return null;
		}
	}
	
}
